package com.powernode.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.powernode.domain.User;
import com.powernode.mapper.UserMapper;
import com.powernode.model.BaseQuery;
import com.powernode.service.UserService;
import com.powernode.util.AuthUtils;
import com.powernode.vo.UserDetailInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User queryUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(Long.valueOf(userId));
    }

    @Override
    public UserDetailInfoVo queryUserDetailInfoById(Integer userId) {
        return userMapper.selectUserDetailInfoById(userId);
    }

    @Override
    public Boolean modifyUserLoginPwd(User user) {
        // 获取登录用户ID
        user.setId(AuthUtils.getLoginUserId());
        user.setEditTime(new Date());
        user.setEditBy(AuthUtils.getLoginUserId());
        user.setLoginPwd(passwordEncoder.encode(user.getLoginPwd()));
        return userMapper.updateByPrimaryKeySelective(user)>0;
    }

    @Override
    public PageInfo<User> queryUserListByPage(Integer current, Integer size) {
        // 设置分页参数
        PageHelper.startPage(current,size);
        // 查询数据
        List<User> userList = userMapper.selectList(new BaseQuery());
        // 创建分页对象
        return new PageInfo<>(userList);
    }

    @Override
    public Boolean saveUser(User user) {
        user.setLoginPwd(passwordEncoder.encode(user.getLoginPwd()));
        user.setCreateTime(new Date());
        user.setCreateBy(AuthUtils.getLoginUserId());
        return userMapper.insertSelective(user)>0;
    }

    @Override
    public Boolean modifyUser(User user) {
        user.setEditTime(new Date());
        user.setEditBy(AuthUtils.getLoginUserId());
        return userMapper.updateByPrimaryKeySelective(user)>0;
    }

    @Override
    public Boolean removeUserById(Integer userId) {
        return userMapper.deleteByPrimaryKey(Long.valueOf(userId))>0;
    }

    @Override
    public Boolean batchRemoveUsersByUserIds(List<Integer> userIds) {
        return userMapper.batchDeleteUsersByIds(userIds)==userIds.size();
    }

    @Override
    public List<User> queryAllUsers() {
        return userMapper.selectAllList();
    }
}
